﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Text.Json.Serialization
{
    /// <summary>
    /// 表示<see langword="DateTime"/>类型的json转换器
    /// </summary>
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        private readonly string _format;

        /// <inheritdoc cref="DateTimeConverter"/>
        /// <param name="format">日期格式</param>
        public DateTimeConverter(string format)
        {
            _format = format;
        }

        /// <inheritdoc/>
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString());
        }

        /// <inheritdoc/>
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(_format));
        }
    }
}
